// pages/chinese/challenge/challenge.js
// 拼音组合数据（声母+韵母）
const pinyinData = [
  // 简单拼音（单韵母）
  { pinyin: "ba", sound: "/sounds/pinyin/ba.mp3", chinese: "爸" },
  { pinyin: "ma", sound: "/sounds/pinyin/ma.mp3", chinese: "妈" },
  { pinyin: "fa", sound: "/sounds/pinyin/fa.mp3", chinese: "发" },
  { pinyin: "da", sound: "/sounds/pinyin/da.mp3", chinese: "大" },
  { pinyin: "ta", sound: "/sounds/pinyin/ta.mp3", chinese: "他" },
  { pinyin: "na", sound: "/sounds/pinyin/na.mp3", chinese: "那" },
  { pinyin: "la", sound: "/sounds/pinyin/la.mp3", chinese: "拉" },
  { pinyin: "ga", sound: "/sounds/pinyin/ga.mp3", chinese: "嘎" },
  { pinyin: "ka", sound: "/sounds/pinyin/ka.mp3", chinese: "卡" },
  { pinyin: "ha", sound: "/sounds/pinyin/ha.mp3", chinese: "哈" },
  { pinyin: "zha", sound: "/sounds/pinyin/zha.mp3", chinese: "扎" },
  { pinyin: "cha", sound: "/sounds/pinyin/cha.mp3", chinese: "查" },
  { pinyin: "sha", sound: "/sounds/pinyin/sha.mp3", chinese: "沙" },
  { pinyin: "za", sound: "/sounds/pinyin/za.mp3", chinese: "杂" },
  { pinyin: "ca", sound: "/sounds/pinyin/ca.mp3", chinese: "擦" },
  { pinyin: "sa", sound: "/sounds/pinyin/sa.mp3", chinese: "撒" },
  
  // 复韵母
  { pinyin: "bai", sound: "/sounds/pinyin/bai.mp3", chinese: "白" },
  { pinyin: "pai", sound: "/sounds/pinyin/pai.mp3", chinese: "拍" },
  { pinyin: "mai", sound: "/sounds/pinyin/mai.mp3", chinese: "买" },
  { pinyin: "dai", sound: "/sounds/pinyin/dai.mp3", chinese: "带" },
  { pinyin: "tai", sound: "/sounds/pinyin/tai.mp3", chinese: "太" },
  { pinyin: "nai", sound: "/sounds/pinyin/nai.mp3", chinese: "奶" },
  { pinyin: "lai", sound: "/sounds/pinyin/lai.mp3", chinese: "来" },
  { pinyin: "gai", sound: "/sounds/pinyin/gai.mp3", chinese: "改" },
  { pinyin: "kai", sound: "/sounds/pinyin/kai.mp3", chinese: "开" },
  { pinyin: "hai", sound: "/sounds/pinyin/hai.mp3", chinese: "海" },
  
  { pinyin: "bao", sound: "/sounds/pinyin/bao.mp3", chinese: "包" },
  { pinyin: "pao", sound: "/sounds/pinyin/pao.mp3", chinese: "跑" },
  { pinyin: "mao", sound: "/sounds/pinyin/mao.mp3", chinese: "猫" },
  { pinyin: "dao", sound: "/sounds/pinyin/dao.mp3", chinese: "到" },
  { pinyin: "tao", sound: "/sounds/pinyin/tao.mp3", chinese: "桃" },
  { pinyin: "nao", sound: "/sounds/pinyin/nao.mp3", chinese: "脑" },
  { pinyin: "lao", sound: "/sounds/pinyin/lao.mp3", chinese: "老" },
  { pinyin: "gao", sound: "/sounds/pinyin/gao.mp3", chinese: "高" },
  { pinyin: "kao", sound: "/sounds/pinyin/kao.mp3", chinese: "考" },
  { pinyin: "hao", sound: "/sounds/pinyin/hao.mp3", chinese: "好" },
  
  { pinyin: "ban", sound: "/sounds/pinyin/ban.mp3", chinese: "班" },
  { pinyin: "pan", sound: "/sounds/pinyin/pan.mp3", chinese: "盘" },
  { pinyin: "man", sound: "/sounds/pinyin/man.mp3", chinese: "满" },
  { pinyin: "dan", sound: "/sounds/pinyin/dan.mp3", chinese: "单" },
  { pinyin: "tan", sound: "/sounds/pinyin/tan.mp3", chinese: "谈" },
  { pinyin: "nan", sound: "/sounds/pinyin/nan.mp3", chinese: "男" },
  { pinyin: "lan", sound: "/sounds/pinyin/lan.mp3", chinese: "蓝" },
  { pinyin: "gan", sound: "/sounds/pinyin/gan.mp3", chinese: "干" },
  { pinyin: "kan", sound: "/sounds/pinyin/kan.mp3", chinese: "看" },
  { pinyin: "han", sound: "/sounds/pinyin/han.mp3", chinese: "汉" },
  
  { pinyin: "bang", sound: "/sounds/pinyin/bang.mp3", chinese: "帮" },
  { pinyin: "pang", sound: "/sounds/pinyin/pang.mp3", chinese: "旁" },
  { pinyin: "mang", sound: "/sounds/pinyin/mang.mp3", chinese: "忙" },
  { pinyin: "dang", sound: "/sounds/pinyin/dang.mp3", chinese: "当" },
  { pinyin: "tang", sound: "/sounds/pinyin/tang.mp3", chinese: "糖" },
  { pinyin: "nang", sound: "/sounds/pinyin/nang.mp3", chinese: "囊" },
  { pinyin: "lang", sound: "/sounds/pinyin/lang.mp3", chinese: "狼" },
  { pinyin: "gang", sound: "/sounds/pinyin/gang.mp3", chinese: "刚" },
  { pinyin: "kang", sound: "/sounds/pinyin/kang.mp3", chinese: "康" },
  { pinyin: "hang", sound: "/sounds/pinyin/hang.mp3", chinese: "航" }
];

Page({
  data: {
    currentLevel: 1,
    levelStars: 0,
    progress: 0,
    inGame: false,
    currentQuestionIndex: 0,
    questionList: [],
    currentQuestion: null,
    answerSlots: [],
    availableLetters: [],
    currentSound: '',
    isPlaying: false,
    hasAnswered: false,
    showResult: false,
    resultIcon: '',
    resultText: '',
    correctCount: 0,
    showCompleteModal: false,
    earnedStars: 0,
    audioContext: null
  },

  onLoad() {
    this.loadLevelProgress();
    
    // 创建音频上下文
    this.audioContext = wx.createInnerAudioContext();
    this.audioContext.onEnded(() => {
      this.setData({
        isPlaying: false
      });
    });
  },

  onUnload() {
    if (this.audioContext) {
      this.audioContext.destroy();
    }
  },

  onShow() {
    this.loadLevelProgress();
  },

  loadLevelProgress() {
    const records = wx.getStorageSync('learningRecords') || {};
    const challengeData = wx.getStorageSync('chineseChallengeData') || {
      currentLevel: 1,
      levelStars: 0
    };
    
    this.setData({
      currentLevel: challengeData.currentLevel || 1,
      levelStars: challengeData.levelStars || 0,
      progress: ((challengeData.currentLevel - 1) * 10) % 100
    });
  },

  startGame() {
    // 生成题目列表（10道题）
    const questionList = this.generateQuestionList();
    
    this.setData({
      inGame: true,
      currentQuestionIndex: 0,
      questionList: questionList,
      correctCount: 0,
      hasAnswered: false
    });
    
    this.generateQuestion();
  },

  generateQuestionList() {
    // 从拼音数据中随机选择10个不重复的拼音
    // 每次重新打乱，确保每次都是随机的
    const shuffled = this.shuffleArray([...pinyinData]);
    return shuffled.slice(0, 10);
  },

  generateQuestion() {
    if (this.data.currentQuestionIndex >= this.data.questionList.length) {
      return;
    }
    
    const question = this.data.questionList[this.data.currentQuestionIndex];
    const pinyinLetters = question.pinyin.split('');
    
    // 创建答案槽位
    const answerSlots = pinyinLetters.map(() => ({ letter: '' }));
    
    // 创建可用字母（打乱顺序）
    let availableLetters = pinyinLetters.map(letter => ({
      letter: letter,
      used: false
    }));
    availableLetters = this.shuffleArray(availableLetters);
    
    this.setData({
      currentQuestion: question,
      answerSlots: answerSlots,
      availableLetters: availableLetters,
      currentSound: question.sound,
      hasAnswered: false,
      showResult: false
    });
  },

  shuffleArray(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  playSound() {
    if (this.data.hasAnswered) return;
    
    if (this.audioContext && this.data.currentSound) {
      this.audioContext.src = this.data.currentSound;
      this.audioContext.play();
      this.setData({
        isPlaying: true
      });
    }
  },

  selectLetter(e) {
    if (this.data.hasAnswered) return;
    
    const index = parseInt(e.currentTarget.dataset.index);
    const letter = this.data.availableLetters[index];
    
    if (!letter || letter.used) return;
    
    // 找到第一个空槽位
    const emptyIndex = this.data.answerSlots.findIndex(slot => !slot.letter || slot.letter === '');
    if (emptyIndex !== -1) {
      this.placeLetterInSlot(index, emptyIndex);
    }
  },

  placeLetterInSlot(letterIndex, slotIndex) {
    const letter = this.data.availableLetters[letterIndex];
    if (!letter || letter.used) return;
    
    // 创建新的答案槽位数组（深拷贝）
    const answerSlots = this.data.answerSlots.map((slot, idx) => {
      if (idx === slotIndex) {
        return { letter: letter.letter };
      }
      return { letter: slot.letter || '' };
    });
    
    // 创建新的可用字母数组（深拷贝）
    const availableLetters = this.data.availableLetters.map((l, idx) => {
      if (idx === letterIndex) {
        return { letter: l.letter, used: true };
      }
      return { letter: l.letter, used: l.used || false };
    });
    
    const isComplete = answerSlots.every(slot => slot.letter && slot.letter !== '');
    
    this.setData({
      answerSlots: answerSlots,
      availableLetters: availableLetters
    });
    
    // 如果填满了，自动检查答案
    if (isComplete) {
      setTimeout(() => {
        const userAnswer = answerSlots.map(slot => slot.letter).join('');
        const correctAnswer = this.data.currentQuestion.pinyin;
        const isCorrect = userAnswer === correctAnswer;
        
        this.checkAnswer(isCorrect);
        
        this.setData({
          hasAnswered: true,
          showResult: true,
          resultIcon: isCorrect ? '✅' : '❌',
          resultText: isCorrect ? '答对了！' : '答错了！'
        });
      }, 500);
    }
  },

  removeLetter(e) {
    if (this.data.hasAnswered) return;
    
    const slotIndex = parseInt(e.currentTarget.dataset.index);
    const slot = this.data.answerSlots[slotIndex];
    
    if (!slot || !slot.letter) return;
    
    // 找到对应的字母并恢复
    const letterIndex = this.data.availableLetters.findIndex(
      (l, i) => l.letter === slot.letter && l.used
    );
    
    if (letterIndex !== -1) {
      const answerSlots = this.data.answerSlots.map((s, idx) => {
        if (idx === slotIndex) {
          return { letter: '' };
        }
        return { letter: s.letter || '' };
      });
      
      const availableLetters = this.data.availableLetters.map((l, idx) => {
        if (idx === letterIndex) {
          return { letter: l.letter, used: false };
        }
        return { letter: l.letter, used: l.used || false };
      });
      
      this.setData({
        answerSlots: answerSlots,
        availableLetters: availableLetters,
        showResult: false
      });
    }
  },

  checkAnswer(isCorrect) {
    if (isCorrect) {
      const correctCount = this.data.correctCount + 1;
      this.setData({
        correctCount
      });
    }
    
    // 更新记录
    const app = getApp();
    app.updateRecords('chinese', isCorrect);
  },

  nextQuestion() {
    if (this.data.currentQuestionIndex >= 9) {
      this.finishLevel();
      return;
    }
    
    const nextIndex = this.data.currentQuestionIndex + 1;
    this.setData({
      currentQuestionIndex: nextIndex,
      hasAnswered: false,
      showResult: false
    });
    
    this.generateQuestion();
  },

  finishLevel() {
    const correctCount = this.data.correctCount;
    const earnedStars = correctCount >= 8 ? 3 : (correctCount >= 6 ? 2 : (correctCount >= 4 ? 1 : 0));
    
    // 更新关卡数据
    const challengeData = wx.getStorageSync('chineseChallengeData') || {
      currentLevel: 1,
      levelStars: 0
    };
    
    if (correctCount >= 6) {
      challengeData.currentLevel = (challengeData.currentLevel || 1) + 1;
    }
    
    if (earnedStars > challengeData.levelStars) {
      challengeData.levelStars = earnedStars;
    }
    
    wx.setStorageSync('chineseChallengeData', challengeData);
    
    this.setData({
      showCompleteModal: true,
      earnedStars: earnedStars,
      inGame: false
    });
  },

  handleLevelComplete() {
    this.setData({
      showCompleteModal: false
    });
    this.loadLevelProgress();
  }
});

